#!/bin/bash

# Kafka Tool 服务状态检查脚本
# 检查后端服务和WebSocket服务的运行状态

echo "=== Kafka Tool 服务状态 ==="
echo ""

# 检查端口状态的函数
check_port_status() {
    local port=$1
    local service_name=$2
    
    local pid=$(lsof -ti:$port 2>/dev/null)
    if [ ! -z "$pid" ]; then
        echo "✅ $service_name (端口 $port): 运行中 (PID: $pid)"
        return 0
    else
        echo "❌ $service_name (端口 $port): 未运行"
        return 1
    fi
}

# 检查PID文件状态的函数
check_pid_file() {
    local pid_file=$1
    local service_name=$2
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            echo "   PID文件: $pid_file (PID: $pid) - 进程运行中"
        else
            echo "   PID文件: $pid_file (PID: $pid) - 进程已停止"
        fi
    else
        echo "   PID文件: $pid_file - 不存在"
    fi
}

# 检查服务状态
websocket_running=false
backend_running=false

echo "🔍 检查服务状态:"
if check_port_status 8001 "WebSocket服务"; then
    websocket_running=true
fi
check_pid_file "logs/websocket.pid" "WebSocket服务"

echo ""
if check_port_status 8002 "Django后端服务"; then
    backend_running=true
fi
check_pid_file "logs/backend.pid" "Django后端服务"

echo ""
echo "📊 服务访问地址:"
if [ "$websocket_running" = true ]; then
    echo "   WebSocket服务: http://127.0.0.1:8001"
else
    echo "   WebSocket服务: 未运行"
fi

if [ "$backend_running" = true ]; then
    echo "   Django后端服务: http://127.0.0.1:8002"
else
    echo "   Django后端服务: 未运行"
fi

echo ""
echo "📋 日志文件:"
if [ -f "logs/websocket.log" ]; then
    echo "   WebSocket日志: logs/websocket.log ($(wc -l < logs/websocket.log) 行)"
else
    echo "   WebSocket日志: 不存在"
fi

if [ -f "logs/backend.log" ]; then
    echo "   后端服务日志: logs/backend.log ($(wc -l < logs/backend.log) 行)"
else
    echo "   后端服务日志: 不存在"
fi

echo ""
echo "🛠️  可用命令:"
echo "   启动服务: ./start_services.sh"
echo "   停止服务: ./stop_services.sh"
echo "   查看WebSocket日志: tail -f logs/websocket.log"
echo "   查看后端日志: tail -f logs/backend.log"

# 总体状态
echo ""
if [ "$websocket_running" = true ] && [ "$backend_running" = true ]; then
    echo "🟢 总体状态: 所有服务正常运行"
elif [ "$websocket_running" = true ] || [ "$backend_running" = true ]; then
    echo "🟡 总体状态: 部分服务运行中"
else
    echo "🔴 总体状态: 所有服务已停止"
fi